# routers/customers.py
from datetime import datetime
from typing import List
from fastapi import APIRouter, Depends, UploadFile, File, Query, Body
from sqlalchemy.orm import Session
from core.database import get_db
from core.security import get_current_user_m
from db.mysql.customers import (CustomerPlatformUpdate, CustomerCreate, H5CustomerCreate,
                                CustomerUpdate, BatchCreateCustomersRequest)
from db.mysql.users import Users
from services.customers import (import_customers_from_excel, get_all_customers, update_customer_platform_service,
                                create_customer_service, batch_update_following_customers_service,
                                get_following_customers,
                                create_or_update_h5_customer, get_chat_messages, update_customer_sv,
                                batch_create_customers_service, update_customer_service, delete_customer_service,
                                run_task_service)
from utils.result import Result
import tempfile
import os
import logging
from core.dependencies import get_redis_service
from services.redis_service import AsyncRedisService

logger = logging.getLogger("app.customers")

router = APIRouter(prefix="/customers", tags=["customers"])


@router.post("/import")
async def import_customers(file: UploadFile = File(...), db: Session = Depends(get_db), current_user: Users = Depends(get_current_user_m),):
    # 验证文件类型
    if not file.filename.endswith(('.xls', '.xlsx')):
        return Result.fail(msg="只支持Excel文件格式 (.xls, .xlsx)")

    # 创建临时文件
    with tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx") as tmp_file:
        tmp_file.write(await file.read())
        tmp_file_path = tmp_file.name

    try:
        # 调用服务层导入数据
        result = await import_customers_from_excel(tmp_file_path, current_user, db)
        return result
    except Exception as e:
        logger.error(f"导入客户数据时发生错误: {str(e)}")
        return Result.fail(msg=f"导入失败: {str(e)}")
    finally:
        # 删除临时文件
        if os.path.exists(tmp_file_path):
            os.unlink(tmp_file_path)


@router.get("/list")
async def get_customers_list(
        page: int = Query(1, ge=1, description="页码"),
        page_size: int = Query(10, ge=1, le=100, description="每页数量"),
        customer_name: str = Query(None, description="客户姓名搜索"),
        phone: str = Query(None, description="手机号搜索"),
        city: str = Query(None, description="城市搜索"),
        source: str = Query(None, description="来源"),
        in_call_task: int = Query(0, description="是否在轮呼任务中 0-不在轮呼任务中，1-在轮呼任务中"),
        user_info: Users = Depends(get_current_user_m),  # 从登录信息获取user_id
        db: Session = Depends(get_db)
):
    # 计算偏移量
    skip = (page - 1) * page_size

    try:
        # user_id = user_info.user_id
        user_id = None if user_info.is_superuser else user_info.user_id
        # 调用服务层获取客户列表
        result = await get_all_customers(skip, page_size, db, customer_name, phone, city, source, in_call_task, user_id)
        return result
    except Exception as e:
        logger.error(f"获取客户列表时发生错误: {str(e)}")
        return Result.fail(msg=f"获取客户列表失败: {str(e)}")


@router.post("/platform/req")
async def update_customer_platform_req(platform_data: CustomerPlatformUpdate, db: Session = Depends(get_db)):
    try:
        req_time = datetime.now()
        # 调用服务层处理
        result = await update_customer_platform_service(platform_data.phone, platform_data.platform,
                                                        platform_data.status, db, request_time=req_time)
        return result
    except Exception as e:
        logger.error(f"更新客户平台信息时发生错误: {str(e)}")
        return Result.fail(msg=f"更新客户平台信息失败: {str(e)}")


@router.post("/platform/add")
async def update_customer_platform_add(platform_data: CustomerPlatformUpdate, db: Session = Depends(get_db)):
    try:
        add_time = datetime.now()
        # 调用服务层处理
        result = await update_customer_platform_service(platform_data.phone, platform_data.platform,
                                                        platform_data.status, db, added_time=add_time)
        return result
    except Exception as e:
        logger.error(f"更新客户平台信息时发生错误: {str(e)}")
        return Result.fail(msg=f"更新客户平台信息失败: {str(e)}")


@router.post("/add")
async def add_customer(cust_data: CustomerCreate, db: Session = Depends(get_db)):
    try:
        # 调用服务层处理
        # 将 Pydantic 模型转换为字典
        customer_dict = cust_data.model_dump(exclude_unset=True)
        result = await create_customer_service(customer_dict, db)
        return result
    except Exception as e:
        logger.error(f"创建客户时发生错误: {str(e)}")
        return Result.fail(msg=f"创建客户失败: {str(e)}")


@router.post("/batch-create")
async def batch_create_customers(
    request: BatchCreateCustomersRequest,
    db: Session = Depends(get_db),
    current_user: Users = Depends(get_current_user_m)
):
    """
    批量创建客户
    
    Args:
        request: 批量创建客户请求
        db: 数据库会话
        current_user: 当前用户
        
    Returns:
        Result: 批量创建结果
    """
    try:
        # 将 Pydantic 模型转换为字典列表
        customers_data = [customer.model_dump(exclude_unset=True) for customer in request.customers]
        
        # 调用服务层处理
        result = await batch_create_customers_service(customers_data, current_user, db)
        return result
    except Exception as e:
        logger.error(f"批量创建客户时发生错误: {str(e)}")
        return Result.fail(msg=f"批量创建客户失败: {str(e)}")


@router.get("/following")
async def get_following_customers_list(
        page: int = Query(1, ge=1, description="页码"),
        page_size: int = Query(10, ge=1, le=100, description="每页数量"),
        customer_name: str = Query(None, description="客户姓名搜索"),
        phone: str = Query(None, description="手机号搜索"),
        city: str = Query(None, description="城市搜索"),
        source: str = Query(None, description="来源"),
        db: Session = Depends(get_db)
):
    """
    获取跟进客户列表
    """
    # 计算偏移量
    skip = (page - 1) * page_size

    try:
        # 调用服务层获取跟进客户列表
        result = await get_following_customers(skip, page_size, db, customer_name, phone, city, source)
        return result
    except Exception as e:
        logger.error(f"获取跟进客户列表时发生错误: {str(e)}")
        return Result.fail(msg=f"获取跟进客户列表失败: {str(e)}")


@router.post("/batch-update-following")
async def batch_update_following_customers(
    request_data: dict = Body(...),
    db: Session = Depends(get_db)
):
    """
    批量更新客户状态为"我跟进的客户"
    
    Args:
        request_data: 包含customer_ids键的字典
        db: 数据库会话
        
    Returns:
        Result: 更新结果
    """
    try:
        customer_ids = request_data.get("customer_ids", [])
        # 调用服务层处理
        result = await batch_update_following_customers_service(customer_ids, db)
        return result
    except Exception as e:
        logger.error(f"批量更新客户状态为'我跟进的客户'时发生错误: {str(e)}")
        return Result.fail(msg=f"批量更新失败: {str(e)}")


# @router.post("/update/call")
# async def update_customer(cust_data: CustomerCreate,db: Session = Depends(get_db)):
#     try:
#         # 调用服务层处理
#         result = await update_customer_callState_by_phone(cust_data.phone, cust_data.call_status, db)
#         return result
#     except Exception as e:
#        logger.error(f"更新客户平台信息时发生错误: {str(e)}")


@router.post("/h5/update")
async def h5_customers(cust_data: H5CustomerCreate, db: Session = Depends(get_db)):
    try:
        # 调用服务层处理
        customer_dict = cust_data.model_dump(exclude_unset=True)
        
        result = await create_or_update_h5_customer(customer_dict, db)
        return result
    except Exception as e:
        logger.error(f"H5客户创建/更新时发生错误: {str(e)}")
        return Result.fail(msg=f"操作失败: {str(e)}")


@router.post("/update")
async def update_customer(
    customer_data: CustomerUpdate,
    db: Session = Depends(get_db)
):
    """
    根据customer_id更新客户信息
    """
    try:
        # 调用服务层处理
        customer_dict = customer_data.model_dump(exclude_unset=True)
        customer_id = customer_dict.pop('customer_id')  # 从数据中提取customer_id
        result = await update_customer_sv(customer_id, customer_dict, db)
        return result
    except Exception as e:
        logger.error(f"更新客户信息时发生错误: {str(e)}")
        return Result.fail(msg=f"更新客户信息失败: {str(e)}")


@router.get("/chat/messages/{session_id}")
async def get_chat_messages_endpoint(
    session_id: str,
    redis_service: AsyncRedisService = Depends(get_redis_service)
):
    """
    根据session_id获取聊天记录
    """
    try:
        # 调用服务层处理
        result = await get_chat_messages(session_id, redis_service)
        return result
    except Exception as e:
        logger.error(f"获取聊天记录时发生错误: {str(e)}")
        return Result.fail(msg=f"获取聊天记录失败: {str(e)}")


@router.put("/{customer_id}")
async def update_customer_by_id(
    customer_id: int,
    customer_data: CustomerUpdate,
    db: Session = Depends(get_db)
):
    """
    更新客户信息
    """
    try:
        # 将 Pydantic 模型转换为字典，并排除未设置的字段
        update_data = customer_data.model_dump(exclude_unset=True)
        
        # 调用服务层处理
        result = await update_customer_service(customer_id, update_data, db)
        return result
    except Exception as e:
        logger.error(f"更新客户信息时发生错误: {str(e)}")
        return Result.fail(msg=f"更新客户信息失败: {str(e)}")


@router.delete("/{customer_id}")
async def delete_customer(
    customer_id: int,
    db: Session = Depends(get_db)
):
    """
    删除客户
    """
    try:
        # 调用服务层处理
        result = await delete_customer_service(customer_id, db)
        return result
    except Exception as e:
        logger.error(f"删除客户时发生错误: {str(e)}")
        return Result.fail(msg=f"删除客户失败: {str(e)}")


@router.post("/task-run")
async def task_run(
        request: BatchCreateCustomersRequest,
        db: Session = Depends(get_db)):
    try:
        # 将 Pydantic 模型转换为字典列表
        customers_data = [customer.model_dump(exclude_unset=True) for customer in request.customers]

        # 调用服务层处理
        result = await run_task_service(customers_data, request.channel, db)
        return result
    except Exception as e:
        logger.error(f"批量创建客户时发生错误: {str(e)}")
        return Result.fail(msg=f"批量创建客户失败: {str(e)}")